using ASP;
using HoWave.Alipay;
using HoWave.Common;
using HoWave.Data.Bll;
using HoWave.Data.Model;
using HoWave.Web;
using HoWave.Web.Shop.Member;
using System;
using System.Collections.Generic;
using System.Data;
using System.Web.Profile;
using System.Web.Script.Serialization;
using System.Web.SessionState;
using System.Web.UI.WebControls;
public class Member_MBF_PayGiftCards : Member, IRequiresSessionState
{
	private JavaScriptSerializer _js = null;
	private UserGiftCardModel _model = null;
	protected HiddenField h_extra_common_param;
	protected DropDownList PayType;
	protected TextBox TxtMoney;
	protected Literal ltr_notice;
	protected Button Button1;
	protected Button Button2;
	protected JavaScriptSerializer js
	{
		get
		{
			if (this._js == null)
			{
				this._js = new JavaScriptSerializer();
			}
			return this._js;
		}
	}
	protected UserGiftCardModel model
	{
		get
		{
			if (this._model == null)
			{
				this._model = new UserGiftCardModel();
			}
			return this._model;
		}
		set
		{
			this._model = value;
		}
	}
	protected DefaultProfile Profile
	{
		get
		{
			return (DefaultProfile)this.Context.Profile;
		}
	}
	protected global_asax ApplicationInstance
	{
		get
		{
			return (global_asax)this.Context.ApplicationInstance;
		}
	}
	protected void Page_Load(object sender, EventArgs e)
	{
		if (!base.IsPostBack)
		{
			string text = Fetch.Get("model");
			this.model = Blls.bllGiftCard.DesToString(text);
			if (this.model.CardNumber == "" || this.model.FaceValue < 0m)
			{
				this.WriteErrMsg("", Language.GetMemberMsg("Voucher/DataIllegal", new string[0]), "");
			}
			this.ltr_notice.Text = string.Format("一张面值为{0}的{1}礼品卡", this.model.FaceValue, Blls.bllUserCardCategory.GetNameByCategory(this.model.FestivalName));
			this.h_extra_common_param.Value = text;
			this.TxtMoney.Text = this.model.FaceValue.ToString();
			this.TxtMoney.ReadOnly = true;
			this.BindPayType();
		}
	}
	protected void BindPayType()
	{
		string key = this.config["AlipayKey"].ToString().Trim();
		OnlinePaySeting onlinePaySeting = new OnlinePaySeting(this.conn);
		this.PayType.DataSource = onlinePaySeting.GetActivePaySeting(key);
		this.PayType.DataBind();
	}
	protected void Button1_Click(object sender, EventArgs e)
	{
		string text = this.config["AlipayPartnerID"].ToString().Trim();
		if (this.PayType.SelectedIndex == -1 || this.PayType.SelectedValue == "")
		{
			this.WriteErrMsg("", "请选择通道！", "");
		}
		int num = Convert.ToInt32(this.PayType.SelectedValue);
		decimal num2 = 0m;
		num2 = Text.ToDecimal(this.TxtMoney.Text);
		if (num2 <= 0m)
		{
			this.WriteErrMsg("", Language.GetMemberMsg("Voucher/MoneyErr", new string[0]), "");
		}
		num2 = decimal.Round(num2, 2);
		if (num < 0)
		{
			this.WriteErrMsg("", Language.Get("Common/NotData"), "");
		}
		PayOnline payOnline = new PayOnline(this.conn);
		string text2 = DateTime.Now.ToString("yyyyMMddhhmmss") + Text.MakePassword(2);
		string text3 = "";
		if (num >= 0)
		{
			if (!payOnline.Add(base.user.UserID, base.user.UserName, 0, text2, num, num2, num2, "", ""))
			{
				this.WriteErrMsg("", Language.Get("Common/Fail", ""), "");
			}
			this.model = Blls.bllGiftCard.DesToString(this.h_extra_common_param.Value);
			if (this.model.RecieveID <= 0)
			{
				this.model.ReceiveEmail = "";
			}
			text3 = string.Concat(new string[]
			{
				this.model.CardNumber,
				"_",
				this.model.BuyID.IsNull(new object[0]),
				"_",
				this.model.RecieveID.IsNull(new object[0])
			});
			this.model.BuyID = (this.model.RecieveID = null);
			Blls.bllGiftCard.Add(this.model);
			if (!Blls.bllGiftCard.Exists(this.model.CardNumber))
			{
				this.WriteErrMsg("saveFail", Language.GetMemberMsg("Voucher/PayError", new string[0]), Fetch.CurrentUrl);
			}
		}
		if (num == 0)
		{
			if (base.user.Balance < num2)
			{
				this.WriteErrMsg("", Language.GetMemberMsg("Order/PayOrder/NotBalance", new string[0]), "");
			}
			IDbDataParameter dbDataParameter = this.conn.CreateParameter("@Remark", DbType.String, "商城币支付礼品卡");
			this.conn.BeginTransaction();
			try
			{
				decimal d = (decimal)this.conn.GetScalar("Select Balance From [HL_User] Where UserID=" + base.user.UserID, new IDbDataParameter[0]);
				string userBalanceKey = Text.GetUserBalanceKey(base.user.UserID, d - num2);
				this.conn.ExecuteTransaction(string.Concat(new object[]
				{
					"Update [HL_User] Set Balance=Balance-",
					num2,
					",EncryptMoney='",
					userBalanceKey,
					"' Where UserID=",
					base.user.UserID
				}));
				this.conn.ExecuteTransaction(string.Concat(new object[]
				{
					"Insert Into HL_AccountDetails(UserID,cMoney,cType,uBalance,CreateTime,Remark) values(",
					base.user.UserID,
					",",
					num2,
					",0,",
					d - num2,
					",getdate(),@Remark)"
				}), new IDbDataParameter[]
				{
					dbDataParameter
				});
			}
			catch (Exception ex)
			{
				this.conn.Rollback();
				ex.WriteErrorLog(new string[0]);
				this.WriteErrMsg("", Language.Get("Common/Fail", ""), "");
			}
			this.conn.Commit();
			base.user.Balance = base.user.Balance - num2;
			payOnline.SetPayOK(text2);
			string[] array = text3.Split(new char[]
			{
				'_'
			});
			if (array.Length < 3)
			{
				this.WriteErrMsg("", Language.GetMemberMsg("Voucher/DataIllegal", new string[0]), "");
			}
			int num3 = 0;
			int num4 = 0;
			string text4 = array[0];
			if (array[1] != "")
			{
				num3 = Convert.ToInt32(array[1]);
			}
			if (array[2] != "")
			{
				num4 = Convert.ToInt32(array[2]);
			}
			int num5 = (int)this.conn.GetScalar("Select UserID From HL_PayOnline WHERE PayNum= '" + text2 + "'", new IDbDataParameter[0]);
			if (num3 == 0)
			{
				num3 = num5;
			}
			if (!this.UpdateUserGiftBuyedCard(text4, num3, num4))
			{
				this.WriteErrMsg("", Language.GetMemberMsg("Voucher/AddGiftError", new string[0]), "");
			}
			if (Blls.bllGiftCard.Exists(text4) && num4 > 0)
			{
				string userNameByid = StaticFun.GetUserNameByid(new int?(num4));
				string userNameByid2 = StaticFun.GetUserNameByid(new int?(base.user.UserID));
				string memberMsg = Language.GetMemberMsg("Voucher/SendGiftEmailContent", new string[]
				{
					userNameByid,
					userNameByid2,
					this.model.BuyTime.ToString(),
					this.config["SiteUrl"].ToString()
				});
				MessageBll messageBll = new MessageBll(this.conn);
				string title = "礼品卡接收提醒";
				messageBll.AddMessage(userNameByid2, "Users", title, memberMsg, 0, 0, 1, 0, userNameByid, "", 1);
				Email email = new Email();
				email.SendEmail(this.config, memberMsg, this.model.ReceiveEmail, Language.GetMemberMsg("Voucher/SendGiftEmailTitle", new string[0]));
			}
			this.WriteSuccessMsg("", "礼品卡购买成功！", "MBF_MyGiftCards.aspx");
		}
		else
		{
			if (num > 0)
			{
				OnlinePaySeting onlinePaySeting = new OnlinePaySeting(this.conn);
				DataTable paySetingByID = onlinePaySeting.GetPaySetingByID(num);
				if (paySetingByID.Rows.Count <= 0)
				{
					this.WriteErrMsg("", Language.Get("Common/NotData"), "");
				}
				string text5 = paySetingByID.Rows[0]["SysStr"].ToString();
				string value = DateTime.Now.ToString("yyyyMMddhhmmss") + Text.MakePassword(2);
				string value2 = "购买礼品卡";
				string text6 = this.ltr_notice.Text;
				if (Convert.ToDecimal(this.TxtMoney.Text.Trim()) != this.model.FaceValue)
				{
					this.WriteErrMsg("", Language.GetMemberMsg("Voucher/DataIllegal", new string[0]), "");
				}
				string value3 = this.TxtMoney.Text.Trim();
				string value4 = "";
				string value5 = "";
				string value6 = "";
				string value7 = "";
				string value8 = "";
				string value9 = "";
				string value10 = "";
				string value11 = "";
				string value12 = text;
				string value13 = this.config["AlipayEmail"].ToString().Trim();
				string value14 = this.config["AlipayKey"].ToString().Trim();
				string value15 = this.config["SiteUrl"].ToString().Trim() + "PayReturn/AliPay/Recharge/paygift_return_url.aspx";
				string value16 = this.config["SiteUrl"].ToString().Trim() + "PayReturn/AliPay/Recharge/paygift_notify_url.aspx";
				SortedDictionary<string, string> sortedDictionary = new SortedDictionary<string, string>();
				sortedDictionary.Add("partner", value12);
				sortedDictionary.Add("key", value14);
				sortedDictionary.Add("seller_email", value13);
				sortedDictionary.Add("return_url", value15);
				sortedDictionary.Add("notify_url", value16);
				sortedDictionary.Add("payment_type", "1");
				sortedDictionary.Add("show_url", value8);
				sortedDictionary.Add("out_trade_no", value);
				sortedDictionary.Add("subject", value2);
				sortedDictionary.Add("body", text6);
				sortedDictionary.Add("total_fee", value3);
				sortedDictionary.Add("paymethod", value4);
				sortedDictionary.Add("defaultbank", value5);
				sortedDictionary.Add("anti_phishing_key", value6);
				sortedDictionary.Add("exter_invoke_ip", value7);
				sortedDictionary.Add("extra_common_param", text3);
				sortedDictionary.Add("buyer_email", value9);
				sortedDictionary.Add("royalty_type", value10);
				sortedDictionary.Add("royalty_parameters", value11);
				Service service = new Service();
				string s = service.Create_direct_pay_by_user(sortedDictionary);
				base.Response.Write(s);
			}
		}
	}
	private bool UpdateUserGiftBuyedCard(string cardnumber, int buyid, int receiveid)
	{
		bool flag = false;
		bool result;
		if (cardnumber == "" || buyid < 1)
		{
			result = false;
		}
		else
		{
			UserGiftCardModel model = Blls.bllGiftCard.GetModel(cardnumber);
			if (model != null)
			{
				this.conn.Execute(string.Concat(new object[]
				{
					"UPDATE [HL_User] SET [Balance] = [Balance]+",
					model.CouponAmount,
					" WHERE [UserID] = ",
					base.user.UserID
				}));
				model.BuyID = new int?(buyid);
				model.RecieveID = new int?(receiveid);
				Blls.bllGiftCard.Update(model);
				UserCardRecordModel userCardRecordModel = new UserCardRecordModel();
				userCardRecordModel.Amount = model.FaceValue;
				userCardRecordModel.Remark = "购买礼品卡";
				userCardRecordModel.CardType = "2";
				userCardRecordModel.UserID = new int?(base.user.UserID);
				userCardRecordModel.CardNumber = cardnumber;
				if (userCardRecordModel.CardNumber != "")
				{
					Blls.bllUserCardRecord.Add(userCardRecordModel);
				}
				if (model.RecieveID > 0)
				{
					userCardRecordModel.UserID = model.RecieveID;
					userCardRecordModel.Remark = "用户赠送您礼品卡";
					Blls.bllUserCardRecord.Add(userCardRecordModel);
					Email email = new Email();
					string memberMsg = Language.GetMemberMsg("Voucher/SendGiftEmailContent", new string[]
					{
						StaticFun.GetUserNameByid(model.RecieveID),
						StaticFun.GetUserNameByid(model.BuyID),
						model.BuyTime.ToString(),
						this.config["SiteUrl"].ToString()
					});
					email.SendEmail(this.config, memberMsg, model.ReceiveEmail, Language.GetMemberMsg("Voucher/SendGiftEmailTitle", new string[0]));
				}
				flag = true;
			}
			result = flag;
		}
		return result;
	}
}
